package com.baizhi.aop;

import com.baizhi.annotation.LogAnnotation;
import com.baizhi.dao.AdminDao;
import com.baizhi.dao.UserLogDao;
import com.baizhi.entity.Admin;
import com.baizhi.entity.UserLog;
import com.baizhi.util.IPKit;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * Created by Administrator on 2019/4/10.
 * 创建aop切面
 * @Configuration声明当前类为配置类
 * @Aspect 声明当前类为切面类
 */
@Configuration
@Aspect
public class LogAspect {
    private Logger logger = LoggerFactory.getLogger(LogAspect.class);

    @Autowired
    private UserLogDao userLogDao;

    /**
     * 1.设置切点  切点设置在注解上
     */
    @Pointcut("@annotation(com.baizhi.annotation.LogAnnotation)")
    public void logPointCut(){}

    /**
     * 2.创建后置增强
     */
    @After("logPointCut()")
    public void logAfter(JoinPoint joinPoint){
        logger.info("开始执行日志记录增强");
//        1.创建CmfzLog对象  赋值
        UserLog userLog = new UserLog();
        userLog.setLogDate(new Date());

//        2.获取session中的管理员对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpSession session = requestAttributes.getRequest().getSession();
        Admin admin = (Admin)session.getAttribute("admin");
        String adminName=admin.getAdminUsername();
        userLog.setLogAdminName(adminName);

//        3.通过工具类获取ip
        String ipAddrByRequest = IPKit.getIpAddrByRequest(requestAttributes.getRequest());
        userLog.setLogIp(ipAddrByRequest);

//        4.通过获取当前方法上的注解 得到日志的内容
//        获取方法签名对象
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
//        获得当前方法对象
        Method method = signature.getMethod();
//        获取加在当前方法上的注解
        LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
        String value = annotation.value();

        userLog.setLogContente(value);
        logger.info("结束记录增强"+userLog);
//        占位符的方式打印日志 在字符串中 写一个{}  后面使用逗号
//        只能在logger打印中使用
        logger.info("结束记录增强:{}和{}",userLog,userLog);
//        插入数据库
        userLogDao.addLog(userLog);
    }
}
